<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="plant in plantList"
              :key="plant.id"
              :label="plant.organizationCode"
              :value="plant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="卷料">
          <select-mesrollmaterialcalculator-input
            :width="200"
            :isMultiple="false"
            :showSelectDevice="rollList"
            :plantId="searchParam.plantId"
            :maxCollapseTags="2"
            :disabled="searchParam.plantId == ''"
            @get-device="(id, object) => getDeviceroll(id, object)"
          />
        </el-form-item>
        <el-form-item label="卷料产成品">
          <search-mesrollmaterialcalculator-input
            :width="400"
            :isMultiple="true"
            :showSelectDevice="materialList"
            :plantId="searchParam.plantId"
            :maxCollapseTags="2"
            :disabled="searchParam.plantId == ''"
            @get-device="(id, object) => getDevice(id, object)"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search1"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset1"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="calculateDialog()"
          >正向推算</el-button
        >
        <el-button type="primary" @click="reverseCalculationDialog()"
          >反向推算</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />

        <el-table-column
          label="外部编号"
          prop="extenalCode"
          sortable
          min-width="150"
        />
        <el-table-column
          label="存货编码"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialCode }} - {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column label="采购订单号" prop="remarks" min-width="150" />

        <el-table-column label="仓库号" prop="warehouseCode" min-width="100" />
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="200"
        />

        <el-table-column
          label="存储类型号"
          prop="storageTypeCode"
          min-width="100"
        />
        <el-table-column
          label="存储类型名称"
          prop="storageTypeName"
          min-width="200"
        />

        <el-table-column
          label="存储区号"
          prop="storageSectionCode"
          min-width="100"
        />

        <el-table-column label="仓位编号" prop="binCode" min-width="120" />
        <el-table-column
          label="总数量"
          prop="totalQuantity"
          min-width="100"
          header-align="center"
          align="right"
        />
        <el-table-column
          label="可用数量"
          prop="availableQuantity"
          min-width="100"
          header-align="center"
          align="right"
        />

        <el-table-column label="数量单位" prop="quantityUnit" min-width="100" />
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <calculateDialog-edit
      :visible="addDialogCalculate.visible"
      :title="addDialogCalculate.title"
      :number="addDialogCalculate.number"
      :materialId="addDialogCalculate.materialId"
      :productionMaterialIds="addDialogCalculate.productionMaterialIds"
      :data="addDialogCalculate.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogCalculate.readvisible"
      @change-visible="changeVisibleCalculate"
    />
    <reverseCalculationDialog-edit
      :visible="addDialogReverseCalculation.visible"
      :title="addDialogReverseCalculation.title"
      :materialId="addDialogReverseCalculation.materialId"
      :productionMaterialIds="addDialogReverseCalculation.productionMaterialIds"
      :data="addDialogReverseCalculation.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogReverseCalculation.readvisible"
      @change-visible="changeVisibleReverseCalculation"
    />
    <!-- <mesplannedbatch-select
      v-model:visible="addDialog123.visible"
      :title="addDialog123.title"
      :isMultiple="true"
      :data="addDialog123.data"
      :is-readonly="addDialog123.readvisible"
      @echo-info="getSelect"
      @change-visible="changeVisible1"
    /> -->
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import dayjs from "dayjs";
import request from "@/utils/request";

defineOptions({
  name: "MESROLLMATERIALCALCULATOR",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/storageunit/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  materialId: "",
  productionMaterialIds: [],
};

const deleteParam = {
  api: "/mes/mesplannedbatch/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);
// 卷料
const rolllList = ref([]);
// 获取选中的数据进行回显并赋值
function getDeviceroll(Ids: string[], Objects: any) {
  if (Ids.length > 0) {
    console.log(Objects);
    searchParam.value.materialId = Ids[0];
  } else {
    searchParam.value.materialId = [];
  }
  console.log(searchParam.value.materialId);
}

// 卷料产成品
const materialList = ref([]);
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any) {
  if (Ids.length > 0) {
    searchParam.value.productionMaterialIds = Ids;
  } else {
    searchParam.value.productionMaterialIds = [];
  }
  console.log(searchParam.value.productionMaterialIds);
}

const search1 = () => {
  if (searchParam.value.materialId == "") {
    ElMessage({
      message: "请选择卷料",
      type: "error",
    });
    return;
  } else {
    search();
  }
};

const reset1 = () => {
  materialList.value = [];
  rollList.value = [];
  tableData.value = [];
  // reset();
};

onMounted(async () => {
  getPlantList();
  // getRollList();
});
// 获取工厂列表
const plantId = ref("");
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  searchParam.value.plantId = plantList.value[0].id;
  plantId.value = plantList.value[0].id;
};
// 获取卷料列表

const rollList: any = ref([]);
const getRollList = async () => {
  const res1 = await request({
    url: "/mdm/mdmmaterial/selectRollMaterial",
    method: "post",
    data: {},
  });
  rollList.value = res1.data;
  console.log("rollList.value", rollList.value);
};

/** 打开正向推算弹窗 */
const addDialogCalculate: any = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  productionMaterialIds: [],
  materialId: "",
  number: 0,
});

const iissCalculate = ref([]);
function calculateDialog(roleObj?: Object) {
  if (searchParam.value.materialId == "") {
    ElMessage.error("请选择卷料");
    return;
  } else if (searchParam.value.productionMaterialIds.length == 0) {
    ElMessage.error("请选择产成品");
    return;
  } else {
    iissCalculate.value = [];
    addDialogCalculate.number = 0;
    tableData.value.forEach((item: any) => {
      ids.value.forEach((i: any) => {
        if (i == item.id) {
          addDialogCalculate.number += item.availableQuantity;
        }
      });
    });
    addDialogCalculate.productionMaterialIds =
      searchParam.value.productionMaterialIds;
    addDialogCalculate.title = "正向推算";
    addDialogCalculate.materialId = searchParam.value.materialId;
    addDialogCalculate.visible = true;
    addDialogCalculate.readvisible = false;
  }
}
function changeVisibleCalculate(value: boolean) {
  addDialogCalculate.visible = value;
  if (!value) {
    addDialogCalculate.data = {};
  }
}
/** 打开反向推算弹窗 */
const addDialogReverseCalculation = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  productionMaterialIds: [],
  materialId: "",
});

const iissReverseCalculation = ref([]);
function reverseCalculationDialog(roleObj?: Object) {
  if (searchParam.value.materialId == "") {
    ElMessage.error("请选择卷料");
    return;
  } else if (searchParam.value.productionMaterialIds.length == 0) {
    ElMessage.error("请选择产成品");
    return;
  } else {
    iissReverseCalculation.value = [];
    tableData.value.forEach((item: any) => {
      ids.value.forEach((i: any) => {
        if (i == item.id) {
          iissReverseCalculation.value.push(item);
        }
      });
    });
    addDialogReverseCalculation.productionMaterialIds =
      searchParam.value.productionMaterialIds;
    addDialogReverseCalculation.materialId = searchParam.value.materialId;
    addDialogReverseCalculation.title = "反向推算";
    addDialogReverseCalculation.visible = true;
    addDialogReverseCalculation.readvisible = false;
  }
}
function changeVisibleReverseCalculation(value: boolean) {
  addDialogReverseCalculation.visible = value;
  if (!value) {
    addDialogReverseCalculation.data = {};
  }
}

const moko = ref([
  {
    id: 1,
    materialCode: "物料编号1",
    figureNumber: "图号1",
    weigth: "",
  },
]);
</script>
